//
//  SchoolAddSecondViewController.swift
//  HoneyBee
//
//  Created by point on 2018/3/9.
//  Copyright © 2018年 point. All rights reserved.
//

import UIKit
import SwiftyJSON

class SchoolAddSecondViewController: BaseViewController {
    private var disposal = Disposal()
    @IBOutlet weak var schoolIdexImageView: UIImageView!
    @IBOutlet weak var schoolNameTextField: UITextField!
    @IBOutlet weak var schoolInfoTextView: UITextView!
    @IBOutlet weak var clickBtn: UIButton!
    @IBOutlet weak var avtiveTextField: UITextField!
    @IBOutlet weak var topHeight: NSLayoutConstraint!
    var currentModel = SchoolDetailModel()
    
    fileprivate var schoolImageViewStr = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.init(hex: "f4f6f8")
        schoolIdexImageView.fastCornerRadius(value: 4)
        topHeight.constant = LayoutCommon.navHeight + 10
        self.title = "发布信息"
        self.schoolIdexImageView.isUserInteractionEnabled = true
        let tapnameGesutre = UITapGestureRecognizer(target: self, action: #selector(nametipFunc(_:)))
        schoolIdexImageView.addGestureRecognizer(tapnameGesutre)
        
        schoolInfoTextView.layer.borderWidth = 0.6
        schoolInfoTextView.layer.borderColor = kColorC4.cgColor
        schoolInfoTextView.layer.cornerRadius = 6
        schoolInfoTextView.clipsToBounds = true
        clickBtn.fastCornerRadius(value: 15)
        addNavObserver()
    }
    
    @IBAction func clickNextBtn(_ sender: UIButton) {
        
        if  currentModel.headImg.count < 0 {
            hudLoadMessage("机构首页图片")
        }
        
        if  currentModel.name.count < 0 {
            hudLoadMessage("机构名称")
        }
        
        if  currentModel.remark.count < 0 {
            hudLoadMessage("机构简介")
        }
        
        if  currentModel.preferential.count < 0 {
            hudLoadMessage("优惠活动")
        }
        
        currentModel.headImg = self.schoolImageViewStr
        currentModel.name = schoolNameTextField.text!
        currentModel.preferential = avtiveTextField.text!
        currentModel.remark = schoolInfoTextView.text!
        
        let current = String().currentTime()
        let dict = [
            "address": currentModel.address,
            "globalAreaCode": currentModel.globalAreaCode,
            "headImg": currentModel.headImg,
            "info": currentModel.info,
            "latitude": currentModel.latitude,
            "longitude": currentModel.longitude,
            "name": currentModel.name,
            "open":  currentModel.isOpen,
            "phone": currentModel.phone,
            "preferential": currentModel.preferential,
            "remark": currentModel.remark,
            "id": UserInfo.shareInstance.userModel().institutionId ,
            "userId": String(UserInfo.shareInstance.userModel().id)] as [String : Any]
            
        let api = kHost + kaddInstitution.apiF(time: current, sign: "")
        self.hudLoad()
        TempNetTool.post(api, parameters: dict, progress: nil, success: { [weak self](result) in
            self?.hudHide()
            if self?.currentModel.modify == false {
                self?.navigationController?.dcPushORPop((self?.classForCoder)!, "SchoolAddDetailViewController", self?.currentModel)
            }else {
                self?.navigationController?.popViewController(animated: true)
            }
            
        }) { [weak self](error) in
            self?.hudError()
        }
        
    }
    
    @objc func nametipFunc(_ ges:UITapGestureRecognizer) {
        alertVC()
    }
    
    
}

// MARK:- 页面监听
extension SchoolAddSecondViewController {
    func addNavObserver() {
        self.dcObjcet?.observe({ [unowned self] (curVal,PreVal) in
            guard let val = curVal as? SchoolDetailModel else  { return }
            self.currentModel = val
            self.configUI()
            
        }).add(to: &disposal)
    }
    
    func configUI() {
        
        if self.currentModel.headImg.count > 0 {
            self.schoolIdexImageView.showImageS(self.currentModel.headImg)
        }
        schoolNameTextField.text = self.currentModel.name
        schoolInfoTextView.text = self.currentModel.remark
        avtiveTextField.text = self.currentModel.preferential
        
        clickBtn.setTitle(self.currentModel.modify == false ? "下 一 步":"完 成", for:.normal )
    }
}

// MARK:- 图片
extension SchoolAddSecondViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    fileprivate func photoClick() {
        if !UIImagePickerController.isSourceTypeAvailable(.photoLibrary)  { return }
        let photoVc = UIImagePickerController()
        photoVc.sourceType = .photoLibrary
        photoVc.delegate = self
        photoVc.allowsEditing = true
        present(photoVc, animated: true, completion: nil)
    }
    
    fileprivate func cameraClick() {
        let pick:UIImagePickerController = UIImagePickerController()
        pick.delegate = self
        pick.sourceType = UIImagePickerController.SourceType.camera
        pick.allowsEditing = true
        present(pick, animated: true, completion: nil)
    }
    
    func alertVC() {
        let alertVc = UIAlertController(title: "选择来源", message: nil, preferredStyle: .actionSheet)
        let photoAction = UIAlertAction(title: "从相册选取", style: .default) { (_) in
            self.photoClick()
        }
        let cameraAction = UIAlertAction(title: "立即拍摄", style: .default) { (_) in
            self.cameraClick()
        }
        let cancelAction = UIAlertAction(title: "取消", style: .default) { (_) in}
        alertVc.addAction(photoAction)
        alertVc.addAction(cameraAction)
        alertVc.addAction(cancelAction)
        present(alertVc, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
        picker.dismiss(animated: true, completion: nil)
        guard var img = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else { return }
        img = img.rotate(aImage: img)
        img = img.square(aImage: img)
        let data = img.jpegData(compressionQuality: 0.5)
        self.hudLoad("上传中..")
        TempNetTool.get(kHost + kgetImgToken, parameters: ["timestamp":"11","sign":"22"], progress: nil, success: { (result) in
            let json = JSON(result ?? "")
            let token = json["uptoken"].string
            let upManager = QNUploadManager()
            upManager?.put(data, key: nil, token: token, complete: { [weak self](info, key, resp) in
                self?.hudHide()
                let json = JSON(resp as Any)
                let url = json["key"].stringValue
                if url.count > 0 {
                    
                    self?.schoolImageViewStr = kqnImageHost + url
                    self?.schoolIdexImageView.showImageS(kqnImageHost + url)
                }else {
                    self?.hudLoadMessage("网络异常")
                }
                
                }, option: nil)
        }) { [weak self](error) in
            self?.hudHide()
            self?.hudLoadMessage("网络异常")
        }
    }
    
}
